package com.sgg.datastructure.stack;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

import java.util.List;
import java.util.Stack;

public class 后缀表达式计算器 {

    public static String cal(String expression) {
        Stack<String> stack = new Stack<>();
        List<String> list = StrUtil.split(expression, StrUtil.SPACE);
        for (String str : list) {
            if (NumberUtil.isNumber(str)) {
                stack.push(str);
            }else {
                Integer pop1 = Integer.valueOf(stack.pop());
                Integer pop2 = Integer.valueOf(stack.pop());
                Integer result = calOne(pop1, pop2, str);
                stack.push(result+"");
            }
        }
        String result = stack.pop();
        System.out.printf("后缀表达式:%s = %s\n",expression,result);
        return result;
    }

    private static Integer calOne(Integer pop1, Integer pop2, String str) {
        Integer result = null;
        switch (str) {
            case "+":
                result = pop2 + pop1;
                break;
            case "-":
                result = pop2 - pop1;
                break;
            case "*":
                result = pop2 * pop1;
                break;
            case "/":
                result = pop2 / pop1;
                break;
            default:
                throw new RuntimeException("参数有误");
        }
        return result;
    }

    public static void main(String[] args) {
        String expression = "3 4 + 5 * 6 -";//29
        cal(expression);
        String expression2 = "4 5 * 8 - 60 + 8 2 / +";//76
        cal(expression2);
    }
}
